/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-09-24 11:09:32
 * @filename : static/logic/nmm/src/views/myProfile.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module){

    require("{component}slider/zepto.sliderDialog.css");
    var myProfileView,userInfo,userObj,nav='myProfile', currentTab='',setMainBool=true,
        mId = 'myProfile',reRender = false, menuName='myProfile',
        imglazyload = require('{component}imglazyload/zepto.imglazyload'),
        sliderDialog = require('{component}slider/zepto.sliderDialog'),
        upload  = require('{component}upload/upload'),
        panel = require('{component}panel/zepto.panel'),
        tplN = require('{view}userNav.tpl'),
        tplHead = require('{view}myProfileHead.tpl'),
        tplPhotoList = require('{view}myProfileTabPhotoList.tpl'),
        tplSD  = require('{view}sliderDialog.tpl'),
        tplAbout  = require('{view}myProfileAbout.tpl'),
        tplDetails  = require('{view}myProfileDetails.tpl'),
        tpl = require('{view}myProfile.tpl');

    myProfileView = Backbone.View.extend({

        el: 'body',

        template : null,
        templateN : null,
        templateHead : null,
        templateAbout : null,
        templateDetails : null,
        templateSD : null,

        initialize: function () {
            this.template = _.template(tpl);
            this.templateN = _.template(tplN);
            this.templateSD = _.template(tplSD);
            this.templateHead = _.template(tplHead);
            this.templateAbout = _.template(tplAbout);
            this.templateDetails = _.template(tplDetails);
            this.templatePhotoList = _.template(tplPhotoList);
        },

        bindEvt : function() {
            var tthis = this,dom=$('#'+mId);
        
            dom.find('.left').on('tap',function(e){
               share.blurChange();   
               e.stopPropagation();
                if (panel.info.state == 'hidden') {
                    panel.show();
                } else {
                    panel.hidden(); 
                }
            }); 
    
            dom.find('.tabTitle').find('li').on('tap',function(){
                var index = $(this).index();
                share.tabSwitch(dom,index);
                if (index == 0 ) {  
                   $('#'+mId).imglazyload({startY : 0,endY: $('#'+mId).height()}); 
                }
            });
       
            dom.find('.photos_list').find('ul').on('tap',function(e){
                var dom = $(e.target).closest('li');
                if (dom.hasClass('photoListLi')) {
                    tthis.sliderDialogDom(dom.index()-1);
                }
            });

            dom.on('tap',function(e){
               if ($(e.target).hasClass('edit')) {  
                  var url = $(e.target).attr('url');
                  window.location.href = '#'+url+'/whole'; 
               }
            });
        },      

        sliderDialogDom : function(index) {
            var tthis = this,loadImg = seajs.data.vars.resourceUrl+'img/blank.png';
            if ($('#sliderDialog').length > 0){$('#sliderDialog').remove()};
            $('body').append(this.templateSD({arr:userObj.pictures,loadImg:loadImg,type:'edit'}));
            $('#sliderDialog').sliderDialog({
                index : index,
                mainPhoto : function(touch){tthis.setMainPhoto(touch)},
                deletePhoto : function(touch){tthis.deletePhoto(touch)} 
            }); 
            $('#sliderDialog').imglazyload({
                startY : 0,
                endY: $('#'+mId).height(),
                transform : false,
                screen : false 
            });
        },

        setMainPhoto : function(touch) {

            var tthis = this,
                sdDom = $('#sliderDialog'),
                from_id = sdDom.find('.li_item').eq(touch.index).find('img').attr('item_id'),
                to_id = userObj.pictures[0].item_id; 

            
            if (from_id !== to_id && setMainBool) {
                setMainBool = false;
                if(window.confirm('Are you sure set this photo for main photo？')) { 
                    share.pageLoad(true,$('body'));
                    var obj = {
                           url : seajs.data.vars.apiAccessUrl+'set_photo_order',
                           type : 'POST',
                           data : {'from_id':from_id,'to_id':to_id},
                           success : function(data) {
                               share.pageLoad(false,$('body'));
                               setMainBool = true;
                               if (data.errcode == 121) {
                                   alert(data.errmsg);
                               } else {
                                    var usr_id = userObj.account.usr_id;
                                    userObj.pictures = tthis.exchangePhoto(userObj.pictures,touch.index,0);  
                                    share.cacheUserInfo(usr_id,userObj);                               
                                    share.updateMainPhoto(usr_id); 
                                    tthis.exchangePhotoLi(touch.index,0);
                                    tthis.userInfoAfter(); 
                               }  
                           }, 
                           error : function(xhr, errorType, error) {
                               share.error('alert','http request failed!'); 
                           }
                        };
                        $.ajax(share.ajaxControl(obj));
                }
            } else if (from_id == to_id) { 
               alert(lang.alreadyMainphoto);
            }
        },
      
        exchangePhotoLi : function(fromNum,toNum) {
            var dom =  $('#'+mId).find('.photoListLi'), 
                tempF = dom.eq(fromNum).prop("outerHTML"),
                tempT = dom.eq(toNum).prop("outerHTML"); 
            dom.eq(fromNum).replaceWith(tempT); 
            dom.eq(toNum).replaceWith(tempF); 
        },

        exchangePhoto : function(arr,fromNum,toNum) {
            var temp  = arr[toNum];
            arr[toNum] = arr[fromNum];
            arr[fromNum] = temp;   
            return arr;
        },

        deletePhoto : function(touch) {
            if(window.confirm('Delete this photo？')) { 
                share.pageLoad(true,$('body'));
                var tthis = this,
                    sdDom = $('#sliderDialog'),
                    item_id = sdDom.find('.li_item').eq(touch.index).find('img').attr('item_id'), 
                    obj = {
                       url : seajs.data.vars.apiAccessUrl+'delete_photo',
                       type : 'POST',
                       data : {'item_id':item_id},
                       success : function(data) {
                           share.pageLoad(false,$('body'));
                           //console.log(data); 
                           if (data.errcode == 121) {
                               alert(data.errmsg);
                           } else {
                                 var usr_id = userObj.account.usr_id;
                                 userObj.pictures.splice(touch.index,1);   
                                 share.cacheUserInfo(usr_id,userObj);

                                 $('#'+mId).find('.photoListLi').eq(touch.index).remove(); 
                                 if (touch.sliderNum > 1) {
                                    if (touch.index == 0) {
                                        share.updateMainPhoto(usr_id); 
                                    }
                                    touch.index =  (touch.index < 1) ? 0 : touch.index-1;
                                    tthis.sliderDialogDom(touch.index); 
                                 } else {
                                    share.updateMainPhoto(usr_id); 
                                    $('#sliderDialog').remove();
                                 }
                                 tthis.userInfoAfter(); 
                           }  
                       }, 
                       error : function(xhr, errorType, error) {
                           share.error('alert','http request failed!'); 
                       }
                    };
                  $.ajax(share.ajaxControl(obj));
            } 
        },

        render: function (obj) {
            if (!share.checkPermission(true)){return;}; 
            share.reRender(reRender,mId);  
            
            if ($('#'+mId).length < 1) { 
                $('body').append(this.template(lang));
                userInfo = share.userInfo();
                this.bindEvt(); 
                this.getAjaxUserInfo(); 
            } else {
                $('#'+mId).css('display','block');
                this.reload(); 
            }
            
            share.panel(panel,this.templateN,mId,menuName); 
            this.setUpload(); 

            if (obj.val == undefined) {
                share.tabSwitch($('#'+mId),0);
                $('#'+mId).imglazyload({startY : 0,endY: $('#'+mId).height()}); 
            } else {
                share.tabSwitch($('#'+mId),obj.val);
            } 

        },

        reload : function() {
            this.userInfoAfter(); 
        },

        getAjaxUserInfo : function(arr) {
            share.pageLoad(true,$('body'));
            var tthis = this,
                obj = {
                   url : seajs.data.vars.apiAccessUrl+'my_profile',
                   type : 'POST',
                   success : function(data) {
                       share.pageLoad(false,$('body')); 
                       if (data.errcode == 121) {
                           alert(data.errmsg);
                       } else {
                           data.defaultImg = share.defalutImg(data.account.gender,'');
                           data.pathImg = seajs.data.vars.resourceUrl+'img/';
                           share.cacheUserInfo(userInfo.usr_id,data);1
                           tthis.userInfoAfter();
                       }  
                   }, 
                   error : function(xhr, errorType, error) {
                       share.error('alert','http request failed!'); 
                   }
			    };
              $.ajax(share.ajaxControl(obj));
        },

        userInfoAfter : function() {
              userObj = JSON.parse(share.getStorage(userInfo.usr_id));
              this.myProfileHeadRender();
              this.myProfilePhotoRender();
              this.myProfileAboutRender();
              this.myProfileDetailsRender();
        },

        myProfileHeadRender : function() {
              userObj.about.headline = (userObj.about.headline == '' || userObj.about.headline == null) ? "You haven't described yourself yet." : userObj.about.headline;
              $('#'+mId).find('.myProfile_head').html(this.templateHead(userObj));
              $('#'+mId).find('.myProfile_head').imglazyload({startY : 0,endY: $(window).height()});
        },

        myProfilePhotoRender : function() {
            $('#'+mId).find('.photos_list ul').html(this.templatePhotoList(userObj));
            $('#'+mId).find('.photos_list ul').imglazyload({startY : 0,endY: $('#'+mId).height()}); 
            this.initUpload();
        },

        myProfileAboutRender : function() {
            var obj = {
               'relationship_status' : this.searchSelect('ms_marital',userObj.about.relationship_status),
               'looking_for' : share.showCheckboxLabel('ms_relation', userObj.about.looking_for)
            };

            userObj.about.about_me = (userObj.about.about_me == null || userObj.about.about_me == '') ? 'Add descriptions to let more people know about you.' : userObj.about.about_me;
            userObj.about.about_my_match = (userObj.about.about_my_match == null || userObj.about.about_my_match == '') ? 'Add descriptions to let more people know about you.' : userObj.about.about_my_match;
            userObj.about.firstidea = (userObj.about.firstidea == null || userObj.about.firstidea == '') ? 'Add descriptions to let more people know about you.' : userObj.about.firstidea;
             

            $('#'+mId).find('.about_content ul').html(this.templateAbout({userObj:userObj,obj:obj}));
        },

        myProfileDetailsRender : function() {
            var obj = {
                height : this.searchSelect('ms_height',userObj.detail.basics.height),
             ethnicity : this.searchSelect('ms_ethnicity',userObj.detail.basics.ethnicity),
                  eyes : this.searchSelect('ms_eyes',userObj.detail.basics.eyes_color),
                  hair : this.searchSelect('ms_hair',userObj.detail.basics.hair_color),
                  body : this.searchSelect('ms_body',userObj.detail.basics.body_type),
                  
                smoker : this.searchSelect('ms_smoker',userObj.detail.lifestyle.smoking),
               drinker : this.searchSelect('ms_drinker',userObj.detail.lifestyle.drinking),
         have_children : this.searchSelect('ms_have_children',userObj.detail.lifestyle.have_children),
             have_pets : this.searchSelect('ms_pets',userObj.detail.lifestyle.have_pets),
         want_children : this.searchSelect('ms_want_children',userObj.detail.lifestyle.want_children),

             education : this.searchSelect('ms_education',userObj.detail.personalinfo.education),
              language : this.searchSelect('ms_language',userObj.detail.personalinfo.language),
            occupation : this.searchSelect('ms_occupation',userObj.detail.personalinfo.occupation),
             political : this.searchSelect('ms_political_beliefs',userObj.detail.personalinfo.political),
              religion : this.searchSelect('ms_religion',userObj.detail.personalinfo.religion),

                income : this.searchSelect('ms_type',userObj.detail.worth.income),
              networth : this.searchSelect('ms_net_worth',userObj.detail.worth.net_worth)

            }
            $('#'+mId).find('.details_content').html(this.templateDetails(obj));
        },

        searchSelect : function(mid,value) {
            var select = share.getLocalStorage(mid);
            for (var i in select) {
                if (select[i].value == value) {
                    return select[i].label; 
                }
            }
        },

        uploadOpt : function() {
            var tthis = this;
            var obj ={
                id : 'profileUploadPhoto',
                filter: 'image',
                maxsize: 2048000,
                url: seajs.data.vars.apiAccessUrl + 'upload_photo',
                onSuccess: function(data) {
                    $('#'+mId).find('.uploading').hide();
                    try {
                        var data = JSON.parse(data);
                        if (parseInt(data.errcode) == 123 || parseInt(data.errcode) == 10) {
                            console.log(data.errmsg); 
                        } else {
                            var usr_id = userObj.account.usr_id;
                                userObj.pictures.push(data.picture);   
                            share.cacheUserInfo(usr_id,userObj);
                            if (data.picture.picno == 0) {
                                share.updateMainPhoto(usr_id);                           
                            }
                            tthis.userInfoAfter();
                        }
                    } catch(err){};

                },
                onError: function(data){console.log(data)},
                onProgress: function(evt){
                },
                onReader: function(evt) { 
                    $('#'+mId).find('.uploading').show();
                } 
            };
            return obj;
        },

        initUpload : function() {
            upload.init(this.uploadOpt());
        },

        setUpload : function() {
            upload.setUploadOpt(this.uploadOpt());
        }
	});

	module.exports = myProfileView;
})

